/*
 * Copyright (c) 2015 DHC Corporation.
 */
package cn.com.dhc.danlu.util;

import java.security.MessageDigest;

/**
 * MD5加密类
 *
 * @author MuWei
 * @version 1.00 2015/02/05 新建
 */
public class MD5 {
    /**
     * 字符串MD5加密
     *
     * @param str
     *         需要加密的字符串
     *
     * @return 加密后的字符串
     */
    public static String getMD5Str (String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance ("MD5");
            messageDigest.reset ();
            messageDigest.update (str.getBytes ("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace ();
        }

        byte[] byteArray = messageDigest != null ? messageDigest.digest () : new byte[0];
        StringBuilder md5StrBuff = new StringBuilder ();

        // 将加密后的byte数组转换为十六进制的字符串,否则的话生成的字符串会乱码
        for (byte aByteArray : byteArray) {
            if (Integer.toHexString (0xFF & aByteArray).length () == 1) {
                md5StrBuff.append ("0").append (Integer.toHexString (0xFF & aByteArray));
            } else {
                md5StrBuff.append (Integer.toHexString (0xFF & aByteArray));
            }
        }

        return md5StrBuff.toString ();
    }
}